package com.yc.controller;
import com.yc.bean.Coupon;
import com.yc.model.ResponseResult;
import com.yc.service.CouponService;
import com.yc.service.OrderBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zwei
 * @create 2024-10-23 15:47
 */
@RestController
@RequestMapping("/cart")
public class CouponController {
    @Autowired
    private CouponService couponService;
    @Autowired
    private OrderBiz orderBiz;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/getCoupon/{userid}")
    public ResponseResult getCoupon(@PathVariable int userid){
        String result=couponService.grabCoupon(userid);
        return ResponseResult.ok().setData(result);
    }
    @GetMapping("/setCoupon")
    public ResponseResult setCoupon(){
        couponService.publishCoupon();
        return ResponseResult.ok().setData("优惠卷发放成功");
    }
    @PostMapping("/getCouponUid/{userid}")
    public ResponseResult getCouponUid(@PathVariable int userid){
        //从redis中获取当前可用的优惠卷
        Coupon result= couponService.getCoupon(String.valueOf(userid));
        //如果没有优惠卷
        if (result==null){
            return ResponseResult.error().setData("没有可用的优惠卷");
        }
        if (result.getCid()==0){
            return ResponseResult.error().setData("优惠卷已被使用");
        }
        return ResponseResult.ok().setData(result);
    }
    @PostMapping("/updateCode/{order_code}")
    public ResponseResult updateCode(@PathVariable String order_code){
        Boolean result=orderBiz.updatePrice(order_code);
        if (result){
            //修改优惠卷状态和过期时间
            Coupon coupon= (Coupon) redisTemplate.opsForValue().get("17");
            if (coupon!=null){
                coupon.setCid(0);
                // 将更新后的 Coupon 对象重新存入 Redis
                // 先获取原来的过期时间
                Long expiration=redisTemplate.getExpire("17");
                // 更新 Coupon 对象
                redisTemplate.opsForValue().set("17", coupon);
                // 设置相同的过期时间
                if (expiration != null) {
                    redisTemplate.expire("17", expiration, TimeUnit.SECONDS);
                }
            }
            return ResponseResult.ok().setData("优惠卷使用成功");
        }
        return ResponseResult.error().setData("优惠卷使用失败");
    }
}
